import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/app/models/category.dart';
import 'package:flutter_app/resources/widgets/category_tab_view_widget.dart';
import 'package:flutter_app/resources/widgets/logo_widget.dart';
import 'package:flutter_app/resources/widgets/search_input_widget.dart';
import 'package:nylo_framework/nylo_framework.dart';
import '/app/controllers/dashboard_controller.dart';
import 'package:flutter_app/resources/widgets/upgrader_widget.dart';
import 'package:upgrader/upgrader.dart';
import 'package:http/http.dart' as http;

class DashboardPage extends NyStatefulWidget<DashboardController> {
  static RouteView path = ("/dashboard", (_) => DashboardPage());

  DashboardPage({super.key}) : super(child: () => _DashboardPageState());
}

class _DashboardPageState extends NyPage<DashboardPage>
    with SingleTickerProviderStateMixin {
  /// [DashboardController] controller
  DashboardController get controller => widget.controller;
  final FocusNode _searchFocusNode = FocusNode();
  TabController? _tabController;
  List<Map<String, String>> firstTab = [
    {"label": "电影", "value": "movie"},
    {"label": "电视剧", "value": "tv"},
  ];

  LoadingStyle get loadingStyle => LoadingStyle.normal(
        child: CupertinoActivityIndicator(),
      );

  Map<String, List<String>> tabs = {};
  late Upgrader upgrader;
  static const String appcastURL =
      'https://raw.githubusercontent.com/larryaasen/upgrader/master/test/testappcast.xml';

  @override
  get init => () async {
        upgrader = MyUpgrader(
          debugLogging: true,
          client: http.Client(),
          storeController: UpgraderStoreController(
            onAndroid: () => UpgraderAppcastStore(appcastURL: appcastURL),
            oniOS: () => UpgraderAppcastStore(appcastURL: appcastURL),
          ),
        );
        // 遍历 firstTab ，请求接口，将数据放入 tabs
        for (var tab in firstTab) {
          Category categoriesResponse =
              await widget.controller.getCategories(tab["value"]!);
          tabs[tab["value"]!] = categoriesResponse.tags!;
        }

        if (tabs.isNotEmpty) {
          _tabController = TabController(
            length: tabs.length,
            vsync: this,
          );
        }
      };

  @override
  void dispose() {
    _searchFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget view(BuildContext context) {
    return MyUpgradeAlert(
      upgrader: upgrader,
      child: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Scaffold(
          appBar: AppBar(
            title: Search(),
          ),
          backgroundColor: Colors.grey[100],
          body: SafeArea(
            child: Column(
              children: [
                CategoryTab(),
              ],
            ),
          ),
          drawer: _buildDrawer(),
        ),
      ),
    );
  }

  Widget _buildDrawer() {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          DrawerHeader(
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
            child: Text(
              '剧能嗨',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          ListTile(
            minTileHeight: 0,
            leading: Icon(
              Icons.video_call_outlined,
              size: 16,
            ),
            trailing: Icon(
              Icons.keyboard_arrow_right,
              size: 16,
            ),
            title: Text(
              '播放设置',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
            onTap: () {
              Navigator.pop(context);
            },
          ),
          ListTile(
            minTileHeight: 0,
            leading: Icon(
              Icons.settings_outlined,
              size: 16,
            ),
            trailing: Icon(
              Icons.keyboard_arrow_right,
              size: 16,
            ),
            title: Text(
              '源设置',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
            onTap: () {
              Navigator.pop(context);
            },
          ),
          ListTile(
            minTileHeight: 0,
            leading: Icon(
              Icons.system_security_update_outlined,
              size: 16,
            ),
            title: Text(
              '检查更新',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
            onTap: () {
              Navigator.pop(context);
            },
          ),
        ],
      ),
    );
  }

  // Search
  Widget Search() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        children: [
          // const Logo(width: 40, height: 40),
          // const SizedBox(width: 16),
          Expanded(
            child: SearchInput(searchFocusNode: _searchFocusNode),
          ),
          const SizedBox(width: 10),
          IconButton(
            icon: const Icon(Icons.history),
            onPressed: () {
              routeTo("/history");
            },
          ),
        ],
      ),
    );
  }

  Widget CategoryTab() {
    return Expanded(
      child: Column(
        children: [
          TabBar(
            indicatorPadding: const EdgeInsets.all(0),
            labelPadding: EdgeInsets.only(bottom: 0.0),
            controller: _tabController,
            labelStyle: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
              color: Colors.black,
            ),
            unselectedLabelStyle: const TextStyle(
              fontWeight: FontWeight.normal,
              color: Colors.black54,
            ),
            indicatorColor: Colors.black,
            indicatorWeight: 2,
            indicatorSize: TabBarIndicatorSize.label,
            splashFactory: NoSplash.splashFactory,
            dividerColor: Colors.transparent,
            onTap: (index) {
              // DefaultTabController.of(context)?.animateTo(0);
            },
            tabs: firstTab.map((entry) => Tab(text: entry["label"])).toList(),
          ),
          SizedBox(
            height: 10,
          ),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: tabs.entries.map((entry) {
                return CategoryTabView(
                    key: ValueKey(entry.key),
                    type: entry.key,
                    secondTab: entry.value);
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
}
